from app import db
from app.models import MoneyFund
from .base import BaseCollector
from datetime import datetime

class MoneyCollector(BaseCollector):
    def __init__(self):
        super().__init__('money')
        self.base_url = 'http://www.etf.group/data'
        
    def collect_all(self):
        """采集所有货币基金数据"""
        try:
            data = self.fetch_data(f'{self.base_url}/api2.php?page=1&limit=9999')
            items = data['rows']['item']
            
            for item in items:
                fund = MoneyFund.query.filter_by(code=item['code']).first()
                if not fund:
                    fund = MoneyFund()
                
                for key, value in item.items():
                    if hasattr(fund, key):
                        setattr(fund, key, value)
                
                fund.updated_at = datetime.utcnow()
                db.session.add(fund)
            
            db.session.commit()
            self.log_success(self.base_url, len(items))
            return True
        except Exception as e:
            self.log_error(self.base_url, str(e))
            return False